package init

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"sync"
	"time"
	"video-srv/basic/config"
	"video-srv/handler/model"
)

func InitDB() {
	mysqlConfig := config.AppCfg.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		mysqlConfig.User, mysqlConfig.Password,
		mysqlConfig.Host, mysqlConfig.Port, mysqlConfig.Database,
	)
	var err error
	var once sync.Once
	once.Do(func() {
		config.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	})
	if err != nil {
		panic(err)
	}
	fmt.Println("数据库连接成功")
	config.DB.AutoMigrate(&model.User{}, &model.Video{},
		&model.Order{}, &model.Member{}, &model.Favorite{},
		&model.Episode{}, &model.CheckVideo{}, &model.EpisodeLog{}, &model.DanMu{}, &model.Comment{}, &model.Log{})
	fmt.Println("迁移成功")
	db, _ := config.DB.DB()
	db.SetMaxIdleConns(10)
	db.SetMaxOpenConns(100)
	db.SetConnMaxLifetime(time.Hour)
}
